package com.zhenyi.dingke.index;

import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.utils.AuthUtils;
import com.utils.DateUtils;
import com.zhenyi.dingke.interceptor.DKAppAuthInterceptor;
import com.zhenyitech.common.model.DkArrange;
import com.zhenyitech.common.model.DkArrangeUser;
import com.zhenyitech.common.model.DkUser;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

@Before(DKAppAuthInterceptor.class)
public class DKAppController extends DKController {

	private final String APP_ID = PropKit.get("PXLM_APP_ID");
	private final String APP_SECRET = PropKit.get("PXLM_APP_SECRET");

	private DkUser getUser() {
		String uid = AuthUtils.getTokenUid(this);
		return DkUser.dao.findById(uid);
	}

	public void rd() {
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
				+ "appid={}&redirect_uri={}&response_type=code&scope={}&state={}#wechat_redirec";
		String redirect = "http://app.cenjiawen.com/dk/app/test";
		url = StrFormatter.format(url, APP_ID, redirect, "snsapi_base", "");
		renderText(url);
	}

	@Clear
	public void aaa() {
		AuthUtils.login("1", this);
		renderSuccess();
	}

	@Clear
	public void wechat() {
		String code = getPara("code");
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
				+ "appid={}&secret={}&code={}&grant_type=authorization_code";
		url = StrFormatter.format(url, APP_ID, APP_SECRET, code);
		String response = HttpKit.get(url);
		// System.out.println(response);
		// JSONObject jsonObject = JSONUtil.parseObj(response);
		// int status = jsonObject.getInt("status");
		// if (status != 200) {
		// renderFailure();
		// return;
		// }
		// String infoStr = jsonObject.getStr("info");
		JSONObject info = JSONUtil.parseObj(response);
		String openId = info.getStr("openid");
		if (StrKit.isBlank(openId)) {
			renderError(404);
			return;
		}
		DkUser user = DkUser.dao.searchFirst("openId", openId);
		boolean isNewUser = false;
		if (user == null) {
			isNewUser = true;
			user = new DkUser();
			user.setOpenId(openId);
			user.save();
		} else {
			if (StrKit.isBlank(user.getName())) {
				isNewUser = true;
			}
			if (StrKit.isBlank(user.getMobile())) {
				isNewUser = true;
			}
		}
		AuthUtils.login(String.valueOf(user.getId()), this);
		renderSuccess(user);
		if (isNewUser) {
			redirect("/dk/app/signup");
		} else {
			redirect("/dk/app/list");
		}
	}

	public void signup() {
		String key = RandomUtil.randomString(16);
		setAttr("key", key);
		setSessionAttr("key", key);
		render("/dk/app/signup.html");
	}

	public void login() {
		String name = getPara("name");
		String mobile = getPara("mobile");
		DkUser user = getUser();
		user.setName(name);
		user.setMobile(mobile);
		user.update();
		renderSuccess(user);
	}

	private final String signupUrl = "/dk/app/signup";

	@Override
	public void list() {
		DkUser user = getUser();
		if (StrKit.isBlank(user.getMobile())) {
			redirect(signupUrl);
			return;
		}
		if (StrKit.isBlank(user.getName())) {
			redirect(signupUrl);
			return;
		}

		String date = getPara("date", DateUtil.today());
		String next = DateUtils.dateFormat(new DateTime(date).plusDays(1).toDate(), DateUtils.YYYYMMDD);
		String previous = DateUtils.dateFormat(new DateTime(date).plusDays(-1).toDate(), DateUtils.YYYYMMDD);

		setAttr("next", next);
		setAttr("previous", previous);
		setAttr("date", date);
		setAttr("week", new DateTime(date).dayOfWeek().get());

		String startTime = date + " 00:00:00";
		String endTime = date + " 23:59:59";
		Kv kv = Kv.create();
		kv.set("startTime", startTime);
		kv.set("endTime", endTime);
		kv.set("userId", getUser().getId());
		setAttr("startTime", startTime);
		setAttr("endTime", endTime);
		SqlPara sqlPara = db.getSqlPara("DKAppArranges", kv);
		List<Record> record = db.find(sqlPara);
		setItems(JsonKit.toJson(record));
		render("/dk/app/list.html");
	}

	public void cancel() {
		Long arrangeId = getParaToLong("arrangeId");
		DkArrange arrange = DkArrange.dao.findById(arrangeId);
		Date startTime = arrange.getStartTime();
		Date now = new Date();
		Long bet = (startTime.getTime() - now.getTime()) / 1000;
		if (bet <= 0) {
			renderMsg("超过取消时间");
			return;
		}
		DkUser user = getUser();
		Long userId = user.getId();
		DkArrangeUser arrangeUser = DkArrangeUser.dao.findById(arrangeId, userId);
		if (arrangeUser == null) {
			LogKit.info("取消失败" + arrangeId + "," + userId);
			renderFailure();
			return;
		}
		arrangeUser.setStatus(0);
		arrangeUser.setCancelTime(new Date());
		arrangeUser.update();
		arrange.updateJoinCount();
		renderSuccess();
		LogKit.info(user.getName() + "取消成功");
	}

	@Override
	public void submit() {
		Long arrangeId = getParaToLong("arrangeId");
		DkArrange arrange = DkArrange.dao.findById(arrangeId);
		Integer isEnable = arrange.getIsEnable();

		Date startTime = arrange.getStartTime();
		Date now = new Date();
		Long bet = (startTime.getTime() - now.getTime()) / 1000;
		if (bet <= 0) {
			renderMsg("很遗憾,已过订课时间");
			return;
		}
		if (!arrange.getLimit().equals(0)) {
			if (arrange.getJoinCount() >= arrange.getLimit()) {
				renderMsg("该课程人数已满,请联系校方人员");
				return;
			}
		}
		if (isEnable.equals(0)) {
			renderMsg("该课程暂不开放订课权限");
			return;
		}
		DkUser user = getUser();
		if (StrKit.isBlank(user.getName())) {
			renderHref(signupUrl, "请填写姓名");
			return;
		}
		if (StrKit.isBlank(user.getMobile())) {
			renderHref(signupUrl, "请填写电话号码");
			return;
		}
		Long userId = user.getId();
		DkArrangeUser dkArrangeUser = DkArrangeUser.dao.findById(arrangeId, userId);
		if (dkArrangeUser == null) {
			dkArrangeUser = new DkArrangeUser();
			dkArrangeUser.setUserId(userId);
			dkArrangeUser.setArrangeId(arrangeId);
			dkArrangeUser.setStatus(1);
			dkArrangeUser.save();
		} else {
			dkArrangeUser.setStatus(1);
			dkArrangeUser.update();
		}
		arrange.updateJoinCount();
		renderSuccess();
	}
}
